import React, { useState, useEffect } from 'react';
import axios from 'axios';

const PatentForm = ({ applicationId }) => {
    const [patents, setPatents] = useState([]);
    const [newPatent, setNewPatent] = useState({
        sequenceNo: '',
        patentName: '',
        patentType: '',
        issuingAuthority: '',
        patentNo: '',
        country: '',
        inventorCount: 0,
        personalRank: 0,
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchPatents = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/patents`);
                setPatents(response.data);
            } catch (error) {
                console.error('Error fetching patents:', error);
            }
        };

        if (applicationId) {
            fetchPatents();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewPatent(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/patents/${editingId}`, newPatent);
                alert('发明专利信息更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/patents`, newPatent);
                alert('发明专利信息添加成功！');
            }
            setNewPatent({
                sequenceNo: '',
                patentName: '',
                patentType: '',
                issuingAuthority: '',
                patentNo: '',
                country: '',
                inventorCount: 0,
                personalRank: 0,
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/patents`);
            setPatents(response.data);
        } catch (error) {
            console.error('Error saving patent:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewPatent(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/patents/${id}`);
            alert('发明专利信息删除成功！');
            setPatents(patents.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting patent:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>发明专利</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>序号:</label>
                    <input type="text" name="sequenceNo" value={newPatent.sequenceNo} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>专利名称:</label>
                    <input type="text" name="patentName" value={newPatent.patentName} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>专利类型:</label>
                    <input type="text" name="patentType" value={newPatent.patentType} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>发证机关:</label>
                    <input type="text" name="issuingAuthority" value={newPatent.issuingAuthority} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>专利号:</label>
                    <input type="text" name="patentNo" value={newPatent.patentNo} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>国家:</label>
                    <input type="text" name="country" value={newPatent.country} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>发明人数量:</label>
                    <input type="number" name="inventorCount" value={newPatent.inventorCount} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>本人排名:</label>
                    <input type="number" name="personalRank" value={newPatent.personalRank} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newPatent.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加发明专利信息</h4>
            <table>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>专利名称</th>
                        <th>专利类型</th>
                        <th>发证机关</th>
                        <th>专利号</th>
                        <th>国家</th>
                        <th>发明人数量</th>
                        <th>本人排名</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {patents.map(info => (
                        <tr key={info.id}>
                            <td>{info.sequenceNo}</td>
                            <td>{info.patentName}</td>
                            <td>{info.patentType}</td>
                            <td>{info.issuingAuthority}</td>
                            <td>{info.patentNo}</td>
                            <td>{info.country}</td>
                            <td>{info.inventorCount}</td>
                            <td>{info.personalRank}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default PatentForm;

